package com.itheima.global;

import com.itheima.po.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author Andy
 * @Description //TODO ControllerAdvice
 * @Date 2022/3/9 9:46 上午
 * @Version 1.0
 **/
@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlException( SQLIntegrityConstraintViolationException ex){
//        Duplicate entry 'zhangsan' for key 'idx_username'
        String message = ex.getMessage();
//        根据异常信息做解析 拿到'zhangsan'重复输入数据
        String[] strArr = message.split(" ");
        if (strArr.length >= 2){
            return R.error("用户名"+strArr[2] + "已存在");
        }
        return R.error("未知异常");
    }

//    瑞吉点餐中 0代表失败 1代表成功 不需要再定义其他的code也行
    @ExceptionHandler(BusinessException.class)
    public R<String> sqlException( BusinessException ex){
//        Duplicate entry 'zhangsan' for key 'idx_username'
        return R.error(ex.getMessage());
    }
}
